<template>
  <div class="traceable-detail">
    <!-- 头部商品信息 -->
    <div class="product-header">
      <div class="left">
        <!-- 商品图片 -->
        <div class="product-image">
          <img :src="productInfo.cover" alt="商品图片" />
        </div>
        <!-- 商品信息 -->
        <div class="product-info">
          <h2>{{ productInfo.goodsName}}</h2>
          <div class="info-row">
            <div class="info-item">
              <span class="label">生产批次：</span>
              <span>{{ productInfo.batch }}</span>
            </div>
            <div class="info-item">
              <span class="label">保质期：</span>
              <span>{{ productInfo.expiration }} 天</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">生产许可证号：</span>
              <span>{{ productInfo.permit }}</span>
            </div>
            <div class="info-item">
              <span class="label">生产企业：</span>
              <span>{{ productInfo.companies }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item full-width">
              <span class="label">产品检验报告：</span>

               <!-- 照片墙 产品检验报告-->
                <el-upload
                  v-model:file-list="fileList"
                  action="http://localhost:5263/api/FileUploadFile"
                  list-type="picture-card"
                  :multiple="false"    
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleReportSuccess"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
                <el-dialog v-model="imgdialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <!-- 按钮区域 -->
        <div class="action-btns">
          <el-button size="small">修改基本信息</el-button>
          <el-button size="small" type="primary" @click="handleDownload">导出溯源码</el-button>
          <el-button size="small" type="danger" @click="backToList">返回列表</el-button>
        </div>
      </div>
    </div>

    <!-- 溯源详情标签页 -->
    <div class="trace-tabs">
      <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
        <el-tab-pane label="养殖信息 (5/5)" name="1" >
            <!-- 养殖基本信息 -->
             <div class="company-info" v-if="showCompanyInfo">
                <div class="section-header">
                  <h3 style="color:cornflowerblue">养殖信息</h3>
                  <el-button link @click="Addbreeding">设置</el-button>
                </div>
                <div class="info-section">
                  <div class="info-row">
                    <div class="info-item">
                      <span class="label">品种：</span>
                      <span>{{Aquacultrue?.variety}}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">来源：</span>
                      <span>{{Aquacultrue?.from}}</span>
                    </div>
                  </div>
                  <div class="info-row">
                    <div class="info-item">
                      <span class="label">饲养天数：</span>
                      <span>{{Aquacultrue?.total_Days}}天</span>
                    </div>
                    <div class="info-item">
                      <span class="label">饲料品牌：</span>
                      <span>{{Aquacultrue?.feed_Brand}}</span>
                    </div>
                  </div>
                   <div class="info-row">
                    <div class="info-item">
                      <span class="label">饲养负责人：</span>
                      <span>{{Aquacultrue?.keeper}}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">出栏日期：</span>
                      <span> {{Aquacultrue?.end_Time}}</span>
                      <!-- {{moment(Aquacultrue?.end_Time).format("YYYY-MM-DD HH:mm:ss")}} -->
                    </div>
                  </div>
                </div>
                 <!-- 养殖信息弹窗设置 -->
               <el-dialog v-model="dialogVisible"title="养殖信息" width="500">
                <el-form
                  ref="ruleFormRef"
                  style="max-width: 600px"
                  :model="ruleForm"
                  :rules="rules"
                  label-width="auto"
                >
                  <el-form-item label="品种" prop="variety">
                    <el-input v-model="ruleForm.variety" />
                  </el-form-item>
                  <el-form-item label="来源" prop="from">
                    <el-input v-model="ruleForm.from" />
                  </el-form-item>
                  <el-form-item label="饲养天数" prop="total_Days">
                    <el-input v-model="ruleForm.total_Days" />
                  </el-form-item>
                  <el-form-item label="饲料品牌" prop="feed_Brand">
                    <el-input v-model="ruleForm.feed_Brand" />
                  </el-form-item>
                  <el-form-item label="饲养负责人" prop="keeper">
                    <el-input v-model="ruleForm.keeper" />
                  </el-form-item>
                  <el-form-item label="出栏时间" prop="end_Time">
                    <el-date-picker
                      v-model="ruleForm.end_Time"
                      type="datetime"
                      placeholder="Pick a date"
                      clearable
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                      保存
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                  </el-form-item>
                </el-form>
               </el-dialog>
             </div>
            <!-- 保健信息 -->
             <div class="company-info" v-if="showCompanyInfo">
                <div class="section-header">
                  <h3 style="color:cornflowerblue">保健信息</h3>
                  <el-button type="primary" plain size="small" icon="Plus" @click="addNewRow">新增行</el-button>
                </div>
                  <el-table :data="healthData" style="width: 100%" border stripe>
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="rearing_Day" label="饲养天数" width="150" align="center">
                      <template #default="scope">
                        <el-input v-if="scope.row.isEdit" v-model="scope.row.rearing_Day" size="small" />
                        <span v-else>{{ scope.row.rearing_Day }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="hygiene_Type" label="保健方式" width="150" align="center">
                      <template #default="scope">
                        <el-input v-if="scope.row.isEdit" v-model="scope.row.hygiene_Type" size="small" />
                        <span v-else>{{ scope.row.hygiene_Type }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="hygiene_Method" label="保健方法" width="150" align="center">
                      <template #default="scope">
                        <el-input v-if="scope.row.isEdit" v-model="scope.row.hygiene_Method" size="small" />
                        <span v-else>{{ scope.row.hygiene_Method }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180" align="center">
                      <template #default="scope">
                        <div v-if="scope.row.isEdit">
                          <el-button size="small" type="success" plain @click="saveRow(scope.row, scope.$index)">保存</el-button>
                          <el-button size="small" plain @click="cancelEdit(scope.row, scope.$index)">取消</el-button>
                        </div>
                        <div v-else>
                          <el-button size="small" type="primary" plain @click="editRow(scope.row)">修改</el-button>
                          <el-button size="small" type="danger" plain @click="removes(scope.$index,scope.row.id,)">删除</el-button>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
             </div>
             <!-- 动检证 -->
             <div class="company-info" v-if="showCompanyInfo">
                    <h3 style="color:cornflowerblue">动检证</h3>
                   <el-upload
                      v-model:file-list="detectFile"
                      action="http://localhost:5263/api/FileUploadFile"
                      list-type="picture-card"
                      :multiple="false"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :on-success="detectReportSuccess"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                     <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
             </div>
             <!-- 企业信息设置 -->
              <div class="company-info" v-if="showCompanyInfo">
                <div class="section-header">
                  <h3 style="color:cornflowerblue">企业信息设置</h3>
                  <el-button link @click="CompanyOpen">设置</el-button>
                </div>
                <div class="info-row">
                    <div class="info-item">
                      <span class="label">养殖场：</span>
                      <span>{{CompanyData?.farms}}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">负责人：</span>
                      <span>{{CompanyData?.header}}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">存栏数量：</span>
                      <span>{{CompanyData?.stockNumber}}</span>
                    </div>
                </div>
                <!-- 企业信息设置弹窗 -->
                <el-dialog v-model="CompanydialogVisible" title="企业信息"width="500">
                    <el-form
                    ref="enterpriseFormRef"
                    style="max-width: 600px"
                    :model="Enterprise"
                    :rules="Companyrules"
                    label-width="auto"
                   >
                  <el-form-item label="养殖场" prop="farms">
                    <el-input v-model="Enterprise.farms" />
                  </el-form-item>
                  <el-form-item label="负责人" prop="header">
                    <el-input v-model="Enterprise.header" />
                  </el-form-item>
                  <el-form-item label="存栏数量" prop="stockNumber">
                    <el-input v-model="Enterprise.stockNumber" />
                  </el-form-item>
                   <el-form-item>
                    <el-button type="primary" @click="EntersubmitForm(enterpriseFormRef)">
                      保存
                    </el-button>
                    <el-button @click="resetForm(enterpriseFormRef)">重置</el-button>
                  </el-form-item>
                  </el-form>
                </el-dialog>
             </div>
             <!-- 企业照片 -->
             <div class="company-info" v-if="showCompanyInfo">
                    <h3 style="color:cornflowerblue">企业照片</h3>
                   <el-upload
                      v-model:file-list="ComapanyFile"
                      action="http://localhost:5263/api/FileUploadFile"
                      list-type="picture-card"
                       :multiple="false"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :on-success="companyReportSuccess"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                     <el-dialog v-model="imgdialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                      </el-dialog>
              </div>
        </el-tab-pane>

        <el-tab-pane label="屠宰信息 (5/5)" name="2">
           <!-- 屠宰信息内容区域 -->
            <!-- 屠宰信息 -->
            <div class="tab-content">
                <div class="section-header">
                  <h3 style="color:cornflowerblue">屠宰信息</h3>
                  <el-button link @click="Seaveslaugther">设置</el-button>
                </div>
                 <div class="info-row">
                    <div class="info-item">
                      <span class="label">批次：</span>
                      <span>{{Slaugtherlist?.batch}}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">到场均重：</span>
                      <span>{{Slaugtherlist?.weight}}公斤</span>
                    </div>
                 </div>
                 <div class="info-row">
                    <div class="info-item">
                      <span class="label">到场时间：</span>
                      <span>{{Slaugtherlist?.feeding_Time}}</span>
                      <!-- {{moment(Slaugtherlist?.feeding_Time).format("YYYY-MM-DD HH:mm:ss")}} -->
                    </div>
                    <div class="info-item">
                      <span class="label">屠宰时间：</span>
                      <span>{{Slaugtherlist?.slaugther_Time}}</span>
                      <!-- {{moment(Slaugtherlist?.slaugther_Time).format("YYYY-MM-DD HH:mm:ss")}} -->
                    </div>
                 </div>
                 <!-- 屠宰信息弹窗设置 -->
                  <el-dialog v-model="slaugtherdialog"title="屠宰信息" width="500">
                    <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px"
                    :model="slaugtherData"
                    :rules="slaugtherrules"
                    label-width="auto"
                  >
                    <el-form-item label="批次" prop="batch">
                      <el-input v-model="slaugtherData.batch" />
                    </el-form-item>
                    <el-form-item label="到场均重" prop="weight">
                      <el-input v-model="slaugtherData.weight" />
                    </el-form-item>
                    <el-form-item label="到场时间" prop="feeding_Time">
                      <el-date-picker
                        v-model="slaugtherData.feeding_Time"
                        type="datetime"
                        placeholder="Pick a date"
                        clearable
                      />
                    </el-form-item>
                    <el-form-item label="屠宰时间" prop="slaugther_Time">
                      <el-date-picker
                        v-model="slaugtherData.slaugther_Time"
                        type="datetime"
                        placeholder="Pick a date"
                        clearable
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="SlaugthersubmitForm(ruleFormRef)">
                        保存
                      </el-button>
                      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                    </el-form-item>
                  </el-form>
                  </el-dialog>
            </div>
               <!--相关资质-->
              <div class="tab-content">
                   <div class="section-header">
                     <h3 style="color:cornflowerblue">相关资质</h3>
                    </div>
                   <el-upload
                      v-model:file-list="slaugtherFile"
                      action="http://localhost:5263/api/FileUploadFile"
                      list-type="picture-card"
                      :multiple="false"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :on-success="slaugtherReportSuccess"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                     <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
             </div>
             <!-- 屠宰企业信息设置 -->
           <div class="tab-content">
                <div class="section-header">
                  <h3 style="color:cornflowerblue">屠宰信息</h3>
                  <el-button link @click="tzcompanyopen">设置</el-button>
                </div>
                <div class="info-row">
                    <div class="info-item">
                      <span class="label">公司名称：</span>
                      <span>{{CompanyData?.companyName}}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">成立时间：</span>
                      <span>{{CompanyData?.setup_Time}}</span>
                      <!-- {{moment(CompanyData?.setup_Time).format("YYYY-MM-DD HH:mm:ss")}} -->
                    </div>
                 </div>
                 <div class="info-row">
                    <div class="info-item">
                      <span class="label">公司地址：</span>
                      <span>{{CompanyData?.companyAdder}}</span>
                    </div>
                 </div>
                  <div class="info-row">
                    <div class="info-item">
                      <span class="label">公司简介：</span>
                      <span>{{CompanyData?.companyDesc}}</span>
                    </div>
                  </div>
                   <!-- 屠宰企业弹窗 -->
              <el-dialog v-model="tzCompanydialogVisible"title="屠宰企业信息" width="500">
                 <el-form
                    ref="tzEnterpriseFormRef"
                    style="max-width: 600px"
                    :model="Enterprise"
                    :rules="Companyrules"
                    label-width="auto"
                  >
                <el-form-item label="公司名称" prop="companyName">
                  <el-input v-model="Enterprise.companyName" />
                </el-form-item>
                <el-form-item label="公司地址" prop="address">
                    <div class="address-container">
                        <el-cascader
                        v-model="addressArray"
                        :options="addressOptions"
                        @change="handleAddressChange"
                        placeholder="请选择省/市/县"
                        style="width: 150px;"
                        />
                        <el-input 
                        v-model="detailAddress" 
                        style="width: 150px;"
                        placeholder="详细地址如乡镇/街道/门牌号"
                        @input="updateFullAddress" 
                        />
                     </div>
                </el-form-item>
                <el-form-item label="成立日期" prop="setup_Time">
                   <el-date-picker
                        v-model="Enterprise.setup_Time"
                        type="datetime"
                        placeholder="Pick a date"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="公司简介" prop="companyDesc">
                  <el-input v-model="Enterprise.companyDesc" type="textarea" />
                </el-form-item>
                 <el-form-item>
                  <el-button type="primary" @click="EntersubmitForm(tzEnterpriseFormRef)">
                    保存
                  </el-button>
                  <el-button @click="resetForm(tzEnterpriseFormRef)">重置</el-button>
                </el-form-item>
                </el-form>
              </el-dialog>
              </div> 
               <!--屠宰企业 照片-->
              <div class="tab-content">
                   <div class="section-header">
                     <h3 style="color:cornflowerblue">企业照片</h3>
                    </div>
                   <el-upload
                      v-model:file-list="slaugCompayFile"
                      action="http://localhost:5263/api/FileUploadFile"
                      list-type="picture-card"
                      :multiple="false"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :on-success="slaugCompanySuccess"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-upload>
                     <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
             </div>
        </el-tab-pane>

        <el-tab-pane label="深加工信息 (0/5)" name="3">
          <!-- 深加工信息内容区域 -->
             <div class="tab-content">
                <div class="section-header">
                  <h3 style="color:cornflowerblue">加工信息</h3>
                  <el-button link @click="processingOpen">设置</el-button>
                 </div>
                  <div class="info-row">
                    <div class="info-item">
                      <span class="label">班组：</span>
                      <span>{{Procesinglist?.team}}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">负责人：</span>
                      <span>{{Procesinglist?.head}}</span>
                    </div>
                 </div>
                 <!-- 加工信息弹窗 -->
                  <el-dialog v-model="processingdialog"title="加工信息" width="500">
                    <el-form
                    ref="processingFormRef"
                    style="max-width: 600px"
                    :model="processingData"
                    :rules="processingrule"
                    label-width="auto"
                  >
                    <el-form-item label="班组" prop="team">
                      <el-input v-model="processingData.team" />
                    </el-form-item>
                    <el-form-item label="负责人" prop="head">
                      <el-input v-model="processingData.head" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="ProcessingsubmitForm(processingFormRef)">
                        保存
                      </el-button>
                      <el-button @click="resetForm(processingFormRef)">重置</el-button>
                    </el-form-item>
                  </el-form>
                  </el-dialog>
             </div>
             <!-- 食品安全信息 -->
               <div class="tab-content">
                       <div class="section-header">
                          <h3 style="color:cornflowerblue">食品安全信息</h3>
                        </div>
                        <el-upload
                            v-model:file-list="Foodsafetyfile"
                            action="http://localhost:5263/api/FileUploadFile"
                            list-type="picture-card"
                            :multiple="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="FoodsafetySuccess"
                        >
                      <el-icon><Plus /></el-icon>
                     </el-upload>
                      <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                   </el-dialog>
               </div>
              <!--供应商信息  -->
                <div class="tab-content">
                  <div class="section-header">
                  <h3 style="color:cornflowerblue">供应商信息</h3>
                </div>

                <!-- ====================原料================== -->
                <div>
                    <div class="info-row">
                        <div class="info-item">
                          <span class="label">【{{supplierData1?.suppliers_Type}}】</span>
                          <el-button  @click="Opensupplier1">设置</el-button>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="info-item">
                          <span class="label">生产批次：</span>
                          <span>{{supplierData1?.batches}}</span>
                        </div>
                    </div>
                </div>
                  <!-- 原料相关资料 -->
                   <div class="tab-content">
                       <div class="section-header">
                          <h3>相关资料</h3>
                        </div>
                        <el-upload
                            v-model:file-list="rawmaterialsfile"
                            action="http://localhost:5263/api/FileUploadFile"
                            list-type="picture-card"
                            :multiple="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="rawmaterialsSuccess"
                        >
                      <el-icon><Plus /></el-icon>
                     </el-upload>
                      <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                   </el-dialog>
                   </div>
                 <!-- ============辅料============== -->
                  <div>
                    <div class="info-row">
                        <div class="info-item">
                          <span class="label">【{{supplierData2?.suppliers_Type}}】</span>
                          <el-button  @click="Opensupplier2">设置</el-button>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="info-item">
                          <span class="label">生产批次：</span>
                          <span>{{supplierData2?.batches}}</span>
                        </div>
                    </div>
                  </div>
                   <!-- 辅料相关资料 -->
                   <div class="tab-content">
                       <div class="section-header">
                          <h3>相关资料</h3>
                        </div>
                        <el-upload
                            v-model:file-list="Accessories"
                            action="http://localhost:5263/api/FileUploadFile"
                            list-type="picture-card"
                            :multiple="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="AccessoriesSuccess"
                        >
                      <el-icon><Plus /></el-icon>
                     </el-upload>
                      <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                   </el-dialog>
                   </div>
                  <!-- ============添加剂============== -->
                  <div>
                    <div class="info-row">
                        <div class="info-item">
                          <span class="label">【{{supplierData3?.suppliers_Type}}】</span>
                          <el-button  @click="Opensipplier3">设置</el-button>
                        </div>
                    </div>
                    <div class="info-row">
                        <div class="info-item">
                          <span class="label">生产批次：</span>
                          <span>{{supplierData3?.batches}}</span>
                        </div>
                    </div>
                  </div>
                   <!-- 添加剂相关资料 -->
                   <div class="tab-content">
                       <div class="section-header">
                          <h3>相关资料</h3>
                        </div>
                        <el-upload
                            v-model:file-list="additivefile"
                            action="http://localhost:5263/api/FileUploadFile"
                            list-type="picture-card"
                            :multiple="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="additiveSuccess"
                        >
                      <el-icon><Plus /></el-icon>
                     </el-upload>
                      <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                   </el-dialog>
                   </div>
                   <!-- 设置供应商弹窗 -->
                   <el-dialog v-model="suppdialogVisible" :title="`供应商信息-${supplierData.suppliers_Type || '添加剂'}`" width="500">
                    <el-form
                      ref="supplieRef"
                      style="max-width: 600px"
                      :model="supplierData"
                      :rules="supplierules"
                      label-width="auto"
                    >
                     <el-form-item label="生产批次" prop="batches">
                        <el-input v-model="supplierData.batches" />
                     </el-form-item>
                  </el-form>
                  <el-form-item>
                    <el-button type="primary" @click="suppliesubmitForm(supplieRef)">
                      保存
                    </el-button>
                    <el-button @click="resetForm(supplieRef)">重置</el-button>
                  </el-form-item>
                   </el-dialog>
                 <!-- 加工企业信息 -->
                  <div class="tab-content">
                      <div class="section-header">
                      <h3 style="color:cornflowerblue">企业信息</h3>
                       <el-button link @click="ProcessingOpen">设置</el-button>
                  </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">公司名称：</span>
                          <span>{{CompanyData?.companyName}}</span>
                        </div>
                        <div class="info-item">
                          <span class="label">生产许可证：</span>
                          <span>{{CompanyData?.permit}}</span>
                        </div>
                      </div>
                  </div>
                   <!-- 深加工企业弹窗 -->
                   <el-dialog v-model="ProcessingdialogVisible" title="深加工企业信息设置" width="500">
                    <el-form
                      ref="enterpriseFormRef"
                      style="max-width: 600px"
                      :model="Enterprise"
                      :rules="Companyrules"
                      label-width="auto"
                    >
                     <el-form-item label="公司名称" prop="companyName">
                        <el-input v-model="Enterprise.companyName" />
                     </el-form-item>
                     <el-form-item label="生产许可证号" prop="permit">
                        <el-input v-model="Enterprise.permit" />
                     </el-form-item>
                  </el-form>
                  <el-form-item>
                    <el-button type="primary" @click="EntersubmitForm(enterpriseFormRef)">
                      保存
                    </el-button>
                    <el-button @click="resetForm(supplieRef)">重置</el-button>
                  </el-form-item>
                   </el-dialog>


                   <!-- 加工企业照片 -->
                   <div class="tab-content">
                       <div class="section-header">
                          <h3>企业照片</h3>
                        </div>
                        <el-upload
                            v-model:file-list="ProcessingEnter"
                            action="http://localhost:5263/api/FileUploadFile"
                            list-type="picture-card"
                            :multiple="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="ProcessingSuccess"
                        >
                      <el-icon><Plus /></el-icon>
                     </el-upload>
                      <el-dialog v-model="imgdialogVisible">
                      <img w-full :src="dialogImageUrl" alt="Preview Image" />
                   </el-dialog>
                   </div>
                </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted ,reactive} from 'vue'
import moment from 'moment'
import { computed } from 'vue'
import { App } from '@/http/interceptors'
import { useRouter, useRoute } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { Plus, Remove } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { qrcanvas } from 'qrcanvas';

const pinia = useCounterStore();
const router = useRouter()
const route = useRoute()


//#region  导出溯源码

// 生成canvas实例

const canvas = qrcanvas({
  data: `http://localhost:5175/traceabledetail?Id=${route.query.Id}&mode=view`
});
// canvas转为dataURL(dase64)
const dateUrl = canvas.toDataURL()
// 保存图片
function saveFile(strData:any, fileType:any, fileName = "name") {
    let saveLink = document.createElement("a");//创建a链接
    saveLink.download = fileName + "." + fileType;//设置下载的文件名和类型
    saveLink.href = strData;//设置下载链接
    saveLink.click();//点击下载
}
function handleDownload(){
console.log('handleDownload');
saveFile(dateUrl,'png','二维码test')
}

//#endregion

//#region   =======================溯源养殖信息==================================
//#region  基础设置

// 标签页控制
// 从localStorage获取上次选择的标签页，如果没有则默认为'1'
const activeTab = ref(localStorage.getItem('traceableActiveTab') || '1')
// 根据当前标签页设置是否显示企业信息
const showCompanyInfo = ref(activeTab.value === '1')
// 处理标签页点击事件
const handleTabClick = (tab:any) => {
  console.log('当前标签页:', tab.props.name)
  // 根据不同标签页显示或隐藏企业信息
  showCompanyInfo.value = tab.props.name === '1'
  // 保存当前选择的标签页到localStorage
  localStorage.setItem('traceableActiveTab', tab.props.name)
  GetCompany(tab); //公司信息加载
  
  
}

// 预览图片
const previewImage = (url:any) => {
  console.log('预览图片:', url)
  // 这里可以实现图片预览逻辑
}
// 返回列表
const backToList = () => {
  router.push('/traceablelist')
}

//#endregion

//#region  头部详细信息

onMounted(() => {
  GoodsDetail();//加载头部信息
  
})

// 修改 GoodsDetail 函数确保顺序正确
const productInfo = ref<any>({})
const GoodsDetail = () => {
  App.get("/api/GoodsGetGoodsDetail", { params: { Id: route.query.Id } }).then(res => {
    if (res.data && res.data.data) {
      productInfo.value = res.data.data 
      console.log("商品详情", productInfo.value)

      // 确保有批次ID才调用其他方法
      if (productInfo.value.batch) {
        // 调用养殖信息加载方法
        GetAquacul();
        // 调用公司信息加载方法
        GetCompany({ props: { name: activeTab.value } });
        // 加载产品检验报告图片
        loadReportImages();
        // 加载动检证图片
        detectReportImages();
        //加载企业照片
        companyReportImages();
        //屠宰信息加载
        GetSlaught();
        //屠宰资质图片
        slaugtherReportImages();
        //屠宰企业照片
        slaugthercompanyImages();
        //加工信息设置
        GetProcessing();
        //加载加工食品安全照片
        FoodsafetyImages();
        //原料
        Getsupplier1();
        rawmaterialsImages();//照片
        //辅料
        Getsupplier2();
        AccessoriesImages();//照片
        //添加剂
        Getsupplier3();
         additiveImages();//照片
        //加工企业照片
         ProcessingEnters();
      }
    } 
  })
}


//#endregion

//#region  养殖信息获取

const Aquacultrue = ref<any>({})

const GetAquacul = () => {
  const bacthid = productInfo.value.batch // 在函数内部获取批次ID
  
  App.get("/api/AquacultureGetAquaculture", { params: { Batch_Id: bacthid } }).then(res => {
    Aquacultrue.value = res.data.data
    Getimmunity();
    
  })
}
//#endregion

//#region  养殖基本信息设置

const dialogVisible = ref(false)

const Addbreeding=()=>{
  dialogVisible.value=true
  ruleForm.batch_Id=productInfo.value.batch 
  ruleForm.variety=Aquacultrue.value?.variety || ""
  ruleForm.from=Aquacultrue.value?.from  || ""
  ruleForm.total_Days=Aquacultrue.value?.total_Days || null
  ruleForm.feed_Brand=Aquacultrue.value?.feed_Brand || ""
  ruleForm.keeper=Aquacultrue.value?.keeper  ||""
  ruleForm.end_Time=Aquacultrue.value?.end_Time  ||""
} 

const ruleFormRef = ref<FormInstance>()



const ruleForm = reactive({
  "batch_Id": "",
  "variety": "",
  "from": "",
  "total_Days": null,
  "feed_Brand": "",
  "keeper": "",
  "end_Time": ""
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  variety: [
    { required: true, message: '品种不能为空', trigger: 'blur' },
  ],
  from: [
    { required: true, message: '来源不能为空', trigger: 'blur' },
  ],
  total_Days: [
    { required: true, message: '养殖天数不能为空', trigger: 'blur' },
  ],
  feed_Brand: [
    { required: true, message: '饲料品牌不能为空', trigger: 'blur' },
  ],
  keeper: [
    { required: true, message: '负责人不能为空', trigger: 'blur' },
  ],
  end_Time: [
    { required: true, message: '出栏时间必选', trigger: 'blur' },
  ],
  
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      console.log("养殖信息设置",ruleForm)
      App.post("/api/AquacultureSaveAquacultrue",ruleForm).then(res=>{
        if(res.data.code==200)
        {
          dialogVisible.value=false
          GoodsDetail();
          ElMessage.success(res.data.message)
        }
        else{
          ElMessage.success(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


//#endregion

//#region  保健信息设置

// 获取保健信息数据
const healthData = ref<any>([])
const Getimmunity=()=>{
const bacthid = productInfo.value.batch // 在函数内部获取批次ID
  App.get("/api/AquacultureGetImmunity",{params:{Batch_Id:bacthid}}).then(res=>{
    healthData.value=res.data.data
  })
}
// 添加新行(空文本)
const addNewRow = () => {
  healthData.value.push({
    rearing_Day: '',
    hygiene_Type: '',
    hygiene_Method: '',
    isEdit: true 
  })
}

// 编辑行
const editRow = (row:any) => {
  //将当前行数据(row)的完整副本存储在row._originalData属性中。保存原始数据的副本用于取消是恢复数据
  //JSON.stringify(row) 将对象转换为JSON字符串
   //JSON.parse(...) 将JSON字符串解析回对象
  // row._originalData = JSON.parse(JSON.stringify(row))
  row.isEdit = true  //变为编辑状态
}

// 保存行
const saveRow = (row:any, index:any) => {
  //校验信息是否填写完整
  if (!row.rearing_Day || !row.hygiene_Type || !row.hygiene_Method) {
    ElMessage.warning('请填写完整的信息')
    return
  }
  
  // 准备保存到数据库的数据
  const saveData = {
    batch_Id: productInfo.value.batch, // 批次ID
    rearing_Day: row.rearing_Day,
    hygiene_Type: row.hygiene_Type,
    hygiene_Method: row.hygiene_Method,
    id: row.id || 0 // 如果有ID则是更新，没有则是新增
  }
  
  // 发送请求保存数据
  App.post("/api/AquacultureCreateImmunity", saveData).then(res => {
    if (res.data.code == 200) {
      row.isEdit = false
      delete row._originalData
      // // 如果是新增，更新行数据中的ID
      // if (!row.id && res.data.data) {
      //   row.id = res.data.data
      // }
      ElMessage.success(res.data.message || '保存成功')
      Getimmunity();
    } else {
      ElMessage.error(res.data.message || '保存失败')
    }
  }).catch(err => {
    console.error('保存失败', err)
    ElMessage.error('网络错误，保存失败')
  })
}

// 取消编辑
const cancelEdit = (row:any, index:any) => {
  if (row._originalData) {
    // 恢复原始数据
    Object.assign(row, row._originalData)
    row.isEdit = false
    delete row._originalData
  } else {
    // 如果是新增的行，直接删除
    healthData.value.splice(index, 1)
  }
}

//移除一行
const removes = (index:any,id:any) => {

  console.log("删除id",id)
  // 如果没有ID，说明是新增但未保存的行，直接删除即可
  if (!id) {
    healthData.value.splice(index, 1)
    return
  }
  
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 发送请求删除数据
    App.delete("/api/AquacultureDeleteImmunity", {params:{Id:id}}).then(res => {
      if (res.data.code == 200) {
        // healthData.value.splice(index, 1)
        ElMessage.success(res.data.message || '删除成功')
        Getimmunity();
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    }).catch(err => {
      console.error('删除失败', err)
      ElMessage.error('网络错误，删除失败')
    })
  }).catch(() => {
    // 取消删除
  })
}


//#endregion

//#endregion

//#region  ==========================溯源屠宰信息==================================

//#region   屠宰信息获取

const Slaugtherlist=ref<any>({})

const GetSlaught=()=>{
  const batchid = productInfo.value.batch
  App.get("/api/SlaughterGetSlaugther", {params: {Batch_Id: batchid}}).then(res => {
      Slaugtherlist.value = res.data.data 
  })
}
//#endregion

//#region   屠宰信息设置

const slaugtherdialog=ref(false)
const Seaveslaugther=()=>{
  slaugtherdialog.value=true
  // 初始化数据
  slaugtherData.batch_Id = productInfo.value.batch 
  slaugtherData.batch = productInfo.value?.batch 
  slaugtherData.weight = Slaugtherlist.value?.weight
  slaugtherData.feeding_Time = Slaugtherlist.value?.feeding_Time 
  slaugtherData.slaugther_Time = Slaugtherlist.value?.slaugther_Time
}
const tzEnterpriseFormRef = ref<FormInstance>()
const slaugtherData=reactive({
   "batch_Id": "",
  "batch": "",
  "weight":null,
  "feeding_Time": "",
  "slaugther_Time": ""
})

//校验规则
const slaugtherrules = reactive<FormRules>({
  batch: [
    { required: true, message: '批次不能为空', trigger: 'blur' },
  ],
  weight: [
    { required: true, message: '均重不能为空', trigger: 'blur' },
  ],
  feeding_Time: [
    { required: true, message: '到场时间不能为空', trigger: 'blur' },
  ],
  slaugther_Time: [
    { required: true, message: '屠宰时间不能为空', trigger: 'blur' },
  ],
})
//保存设置
const SlaugthersubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      App.post("/api/SlaughterSeaveSlaugther",slaugtherData).then(res=>{
        if(res.data.code==200)
        {
          slaugtherdialog.value=false
           GetSlaught();
           ElMessage.success(res.data.message)
        }
        else
        {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//#endregion

//#endregion

//#region  ===========================溯源加工信息===============================

//#region    加工基本信息设置

const processingdialog=ref(false)
const processingFormRef = ref<FormInstance>()
const processingOpen=()=>{
   processingdialog.value=true
   processingData.team=Procesinglist.value.team
   processingData.head=Procesinglist.value.head
}

const processingData=reactive({
  "batch_Id": "",
  "team": "",
  "head": ""
})
//校验
const processingrule = reactive<FormRules>({
    team: [
    { required: true, message: '班组不能为空', trigger: 'blur' },
    ],
    head: [
    { required: true, message: '负责人不能为空', trigger: 'blur' },
    ],
})

const ProcessingsubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      processingData.batch_Id=productInfo.value.batch
      App.post("/api/ProcessingSeaveProcessing",processingData).then(res=>{
        if(res.data.code==200)
        {
          processingdialog.value=false
           GetProcessing();
          ElMessage.success(res.data.message)
        }
        else
        {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//#endregion

//#region    加工信息获取

const Procesinglist=ref<any>([])


const GetProcessing=()=>{
  const batchid=productInfo.value.batch
  App.get("/api/ProcessingGetProcessing",{params:{Batch_Id:batchid}}).then(res=>{
    Procesinglist.value=res.data.data
  })
}
//#endregion

//#region  供应商信息获取

//原料
const supplierData1=ref<any>([])
const Getsupplier1=()=>{
  App.get("/api/ProcessingGetSupplier",{params:{
    Batch_Id:productInfo.value.batch,
    Suppliers_Type:"原料"

  }}).then(res=>{
    supplierData1.value=res.data.data
  })
}
//辅料
const supplierData2=ref<any>([])
const Getsupplier2=()=>{
  App.get("/api/ProcessingGetSupplier",{params:{
    Batch_Id:productInfo.value.batch,
    Suppliers_Type:"辅料"

  }}).then(res=>{
    supplierData2.value=res.data.data
  })
}
//添加剂
const supplierData3=ref<any>([])
const Getsupplier3=()=>{
  App.get("/api/ProcessingGetSupplier",{params:{
    Batch_Id:productInfo.value.batch,
    Suppliers_Type:"添加剂"

  }}).then(res=>{
    supplierData3.value=res.data.data
  })
}

//#endregion

//#region  供应商信息设置

const suppdialogVisible=ref(false)

const Opensupplier1=()=>{
suppdialogVisible.value=true
supplierData.batch_Id=productInfo.value.batch
supplierData.suppliers_Type="原料"
supplierData.batches=supplierData1.value?.batches||""
}

const Opensupplier2=()=>{
suppdialogVisible.value=true
supplierData.batch_Id=productInfo.value.batch
supplierData.suppliers_Type="辅料"
supplierData.batches=supplierData2.value?.batches||""
}

const Opensipplier3=()=>{
suppdialogVisible.value=true
supplierData.batch_Id=productInfo.value.batch
supplierData.suppliers_Type="添加剂"
supplierData.batches=supplierData3.value?.batches||""
}

const supplierData=reactive({
  "batch_Id": "",
  "suppliers_Type": "",
  "batches": ""
})
const supplieRef = ref<FormInstance>()
//校验
const supplierules = reactive<FormRules>({
   batches: [
    { required: true, message: '批次不能为空', trigger: 'blur' },
  ],
})

const suppliesubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      App.post("/api/ProcessingSeaveSupplier",supplierData).then(res=>{
        if(res.data.code==200)
        {
          suppdialogVisible.value=false
          // 根据供应商类型刷新对应的数据
          if (supplierData.suppliers_Type === "原料") {
            Getsupplier1();
          } else if (supplierData.suppliers_Type === "辅料") {
            Getsupplier2();
          } else if (supplierData.suppliers_Type === "添加剂") {
            Getsupplier3();
          }
          ElMessage.success(res.data.message)
        }
        else{
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//#endregion



//#endregion

//#region  企业信息设置
// =======养殖企业信息=========
const CompanydialogVisible = ref(false)
const CompanyOpen=()=>{
  CompanydialogVisible.value=true
  Enterprise.batch_Id=productInfo.value.batch
  Enterprise.traceable_Id=1
  Enterprise.farms=CompanyData.value?.farms||""
  Enterprise.header=CompanyData.value?.header||""
  Enterprise.stockNumber=CompanyData.value?.stockNumber||null
}
//=======屠宰企业设置========
const tzCompanydialogVisible = ref(false)
const tzcompanyopen=()=>{
  tzCompanydialogVisible.value=true
   Enterprise.batch_Id=productInfo.value.batch
   Enterprise.traceable_Id=2
  Enterprise.companyName=CompanyData.value?.companyName||""
  Enterprise.companyAdder=fullAddress.value //将拼接的完整地址赋值给字段
  Enterprise.setup_Time=CompanyData.value?.setup_Time ||null
  Enterprise.companyDesc=CompanyData.value?.companyDesc||""

  //判断是否获取到完整地址，有的话调用反填解析地址的方法
  if (CompanyData.value?.companyAdder) {
    parseAddress(CompanyData.value.companyAdder);
  } else {
    // 清空地址相关字段
    addressArray.value = [];
    detailAddress.value = '';
  }
}
//#region  =====================省市县地址处理=====================
// 地址相关数据
const addressArray = ref<any>([]) // 存储省市县的选择值数组
const detailAddress = ref<any>('') // 详细地址
const fullAddress = ref<any>('') // 完整地址，用于保存到数据库

// 省市县选项数据
const addressOptions = ref([
  {
    value: '四川省',
    label: '四川省',
    children: [
      {
        value: '巴中市',
        label: '巴中市',
        children: [
          {
            value: '通江县',
            label: '通江县',
          }
        ]
      },
      {
        value: '第三市',
        label: '第三市',
      },
      {
        value: '反对市',
        label: '反对市',
      }
    ]
  }
])

// 当省市县选择变化时
const handleAddressChange = () => {
  updateFullAddress()
}

//拼接级联和详细地址
const updateFullAddress = () => {
  // 拼接省市县
  const selectedAddress = addressArray.value.join(' ').toString();
  // 拼接详细地址
  fullAddress.value = selectedAddress + ' ' + detailAddress.value
}


// 从完整地址解析为省市县和详细地址
const parseAddress = (fullAddr: string) => {
  if (!fullAddr) return;
  // 分割地址字符串
  const parts = fullAddr.split(' ');
  // 查找省市县在addressOptions中的匹配项
  if (parts.length >= 3) {
    // 提取省市县
    const province = parts[0];
    const city = parts[1];
    const county = parts[2];
    
    // 设置级联选择器的值
    addressArray.value = [province, city, county];
    
    // 如果有详细地址部分，设置到详细地址输入框
    if (parts.length > 3) {
      detailAddress.value = parts.slice(3).join(' ');
    } else {
      detailAddress.value = '';
    }
  }
}
//#endregion

//============深加工企业信息================
const ProcessingdialogVisible = ref(false)

const ProcessingOpen=()=>{
  ProcessingdialogVisible.value=true
   Enterprise.batch_Id=productInfo.value.batch
  Enterprise.traceable_Id=3
   Enterprise.companyName=CompanyData.value.companyName || ""
  Enterprise.permit=CompanyData.value.permit
}



const enterpriseFormRef = ref<FormInstance>()
const Enterprise = reactive({
  "batch_Id": "",   //批次
  "traceable_Id":0,  //溯源类型
  "farms": "",        //1养殖场
  "header": "",       //1负责人
  "stockNumber": null,  //1存栏数量
  "companyName": "",   //2公司名称
  "companyAdder": "",  //2公司地址
  "setup_Time": null,   //2成立时间
  "companyDesc": "",    ///2公司简介
  "permit": ""          //3生产许可证号
})


//公司表单校验
const Companyrules = reactive<FormRules>({
  farms: [
    { required: true, message: '养殖场不能为空', trigger: 'blur' },
  ],
  header: [
    { required: true, message: '负责人不能为空', trigger: 'blur' },
  ],
  stockNumber: [
    { required: true, message: '存栏数量不能为空', trigger: 'blur' },
    { min: 1, max: 5, message: '只能输入1-5位数字', trigger: 'blur' },
  ],
   companyName: [
    { required: true, message: '公司名称不能为空', trigger: 'blur' },
  ],
    setup_Time: [
    { required: true, message: '成立时间不能为空', trigger: 'blur' },
  ],
   permit: [
    { required: true, message: '生产许可证号不能为空', trigger: 'blur' },
  ],
})

const EntersubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      Enterprise.companyAdder=fullAddress.value
     App.post("/api/CommonCreateCompany",Enterprise).then(res=>{
      if(res.data.code==200)
      {
         CompanydialogVisible.value=false  //养殖企业弹窗
         tzCompanydialogVisible.value=false //屠宰企业弹窗
         ProcessingdialogVisible.value=false //深加工企业弹窗
         GetCompany({ props: { name: activeTab.value } });
         ElMessage.success(res.data.message)
      }
      else
      {
         ElMessage.error(res.data.message)
      }
     })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//#endregion

//#region  获取企业信息

const CompanyData=ref<any>([])
const GetCompany = (tab: any) => {
  const tagId = tab.props.name // 区分标签页Id
  console.log("获取企业信息的标签",tagId)
  const bacthid = productInfo.value?.batch // 在函数内部获取批次ID
  App.get("/api/CommonGetCompany", { params: { Batch_Id: bacthid, Traceable_Id: tagId } }).then(res => {
        CompanyData.value = res.data.data
    })
}

//#endregion

//#region  完善度

// const moduleCount = 5

// const breedFilled = computed(() => !!Aquacultrue.value && Object.keys(Aquacultrue.value).length > 0)
// const healthFilled = computed(() => Array.isArray(healthData.value) && healthData.value.length > 0)
// const animalCheckFilled = computed(() => Array.isArray(detectFile.value) && detectFile.value.length > 0)
// const CompanyFilled=computed(()=>Array.isArray(CompanyData.value) && CompanyData.value.length>0)
// const yzcompanyfilled=computed(()=>Array.isArray(ComapanyFile.value) && ComapanyFile.value.length>0)


// const completeness = computed(() => {
//   let filledCount = 0
//   if (breedFilled.value) filledCount++
//   if (healthFilled.value) filledCount++
//   if (animalCheckFilled.value) filledCount++
//   if(CompanyFilled.value)filledCount++
//   if(yzcompanyfilled.value)filledCount++
//   return Math.round((filledCount / moduleCount) * 100)

// })

//#endregion


//#region  获取照片墙信息

const dialogImageUrl = ref('')
const imgdialogVisible=ref(false)//图片弹窗

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log("图片路由",uploadFile, uploadFiles)
  const url =uploadFile.url
  const batchid =productInfo.value.batch
  App.delete("/api/CommonDeleteimage",{params:{Batch_Id:batchid,Imgurl:url}}).then(res=>{
      if(res.data.code==200)
    {
      GoodsDetail();//加载头部信息
      ElMessage.success(res.data.message)
    }
    else{
      ElMessage.error(res.data.message)
    }
  })
}
//图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  imgdialogVisible.value = true
}


//#region    ==================上传养殖产品检验证====================
const fileList = ref<any[]>([])//接收图片数组

// 上传成功处理
const handleReportSuccess = (response: any, file: any) => {
  console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id: 1, // 1表示养殖信息
      ImgType: '1', // 1表示产品检验报告
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    // 调用接口保存图片信息到数据库
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
        loadReportImages()
      } else {
        ElMessage.error(res.data.message)
      }
    })

}

// 查询获取产品检验报告图片
const loadReportImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 1, // 1表示养殖信息
      ImgType: '1' // 1表示产品检验报告
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      fileList.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region    ==================上传养殖动检证照片===================
const detectFile=ref<any[]>([])  //接收动检图片列表

//上传方法
const detectReportSuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id: 1, // 1表示养殖信息
      ImgType: '2', // 1表示养殖动检证照片
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
        detectReportImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
}

// 查询获取产品检验报告图片
const detectReportImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 1, // 1表示养殖信息
      ImgType: '2' // 1表示产品检验报告
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      detectFile.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region   ==================上传养殖企业照片=====================
const ComapanyFile=ref<any[]>([])  //接收养殖企业照片列表

//上传方法
const companyReportSuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id: 1, // 1表示养殖信息
      ImgType: '3', // 1表示养殖企业照片
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
        companyReportImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
}
// 查询获取养殖企业照片
const companyReportImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 1, // 1表示养殖信息
      ImgType: '3' // 3表示养殖企业照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      ComapanyFile.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region   ==================上传屠宰相关资质照片==================
const slaugtherFile=ref<any[]>([])  //接收屠宰相关资质照片列表

//上传方法
const slaugtherReportSuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id: 2, // 1表示屠宰信息
      ImgType: '1', // 1表示屠宰相关资质照片
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
        slaugtherReportImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
}

// 查询获取屠宰相关资质照片
const slaugtherReportImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 2, // 1表示养殖信息
      ImgType: '1' // 1表示屠宰相关资质照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      slaugtherFile.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion 

//#region   ==================上传屠宰企业照片=======================
const slaugCompayFile=ref<any[]>([])  //接收屠宰企业照片列表
//上传方法
const slaugCompanySuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id: 2, // 2表示屠宰信息
      ImgType: '2', // 2表示屠宰企业照片
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
       slaugthercompanyImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
  
}
// 查询获取屠宰企业图片
const slaugthercompanyImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 2, // 2表示屠宰信息
      ImgType: '2' // 2表示屠宰企业照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      slaugCompayFile.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region   ==================上传加工食品安全信息照片=================
const Foodsafetyfile=ref<any[]>([])  //接收加工食品安全列表

//上传
const FoodsafetySuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id:3, // 3表示加工信息
      ImgType: '1', // 1表示食品安全信息
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
         FoodsafetyImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
}

// 查询获取屠宰企业图片
const FoodsafetyImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 3, // 3表示加工信息
      ImgType: '1' // 1表示食品安全照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      Foodsafetyfile.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region   ====================上传供应商原料图片====================
const rawmaterialsfile=ref<any[]>([])  //接收加工原料列表

//上传
const rawmaterialsSuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id:3, // 3表示加工信息
      ImgType: '2', // 2表示原料信息
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
        rawmaterialsImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
}
// 查询获取加工原料图片
const rawmaterialsImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 3, // 3表示加工信息
      ImgType: '2' // 2表示原料照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      rawmaterialsfile.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region   ===================上传供应商辅料图片=====================
const Accessories=ref<any[]>([])  //接收加工辅料图片
 
//上传
const AccessoriesSuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id:3, // 3表示加工信息
      ImgType: '3', // 3表示辅料信息
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
        AccessoriesImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
}
// 查询获取屠宰企业图片
const AccessoriesImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 3, // 3表示加工信息
      ImgType: '3' // 3表示辅料照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      Accessories.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region ====================上传供应商添加剂图片=================
const additivefile=ref<any[]>([])  //接收添加剂图片
//上传
const additiveSuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id:3, // 3表示加工信息
      ImgType: '4', // 4表示添加剂信息
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
       additiveImages();
      } else {
        ElMessage.error(res.data.message)
      }
    })
}
// 查询获取屠宰企业图片
const additiveImages = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 3, // 3表示加工信息
      ImgType: '4' // 4表示添加剂照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      additivefile.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion

//#region  =====================上传加工企业照片==================
const ProcessingEnter=ref<any[]>([])  //接收添加剂图片

//上传
const ProcessingSuccess=(response:any)=>{
   console.log('上传成功响应:', response)
    // 获取上传后的图片URL，从服务器响应中获取
    const imgUrl = response;
    // 构建要保存到数据库的图片信息
    const imageData = {
      batch_Id: productInfo.value.batch, // 批次ID
      traceable_Id:3, // 3表示加工信息
      ImgType: '5', // 4表示加工企业信息
      Imgurl: imgUrl // 使用服务器返回的图片URL
    }
    App.post("/api/CommonUpImages", imageData).then(res => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.message)
        // 保存成功后重新加载图片列表
       ProcessingEnters();
      } else {
        ElMessage.error(res.data.message)
      }
    })
  
}
// 查询获取屠宰企业图片
const ProcessingEnters = () => {
  // 确保批次ID存在
  if (!productInfo.value || !productInfo.value.batch) {
    console.warn('批次ID不存在，无法加载图片')
    return
  }
  // 调用接口获取图片列表
  App.get("/api/CommonGetImagelist", {
    params: {
      Batch_Id: productInfo.value.batch,
      Traceable_Id: 3, // 3表示加工信息
      ImgType: '5' // 4表示加工企业照片
    }
  }).then(res => {
    if (res.data.code === 200 && res.data.data) {
      // 转换为el-upload需要的格式
      ProcessingEnter.value = res.data.data.map((item: any) => {
        // 尝试多种可能的字段名
        const imageUrl = item.imgurl || item.Imgurl || item.imgUrl || item.ImgUrl || item.url || '';
        return {
          name: imageUrl ? imageUrl.split('/').pop() : '图片',
          url: imageUrl,
          // 保存原始数据，以便后续操作
          raw: item
        }
      })
    } else {
      console.warn(res.data.message)
    }
  })
}
//#endregion


//#endregion


</script>



<style scoped>
/* 基础布局样式 */
.traceable-detail {
  padding: 20px;
}
.traceable-detail {
  padding: 20px;

}

/* 头部商品信息区域 */
.product-header {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.product-header .left {
  display: flex;
}

.product-image {
  width: 150px;
  height: 150px;
  margin-right: 20px;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 标签页样式 */
.trace-tabs {
  margin-bottom: 20px;
}

/* 标签页内容样式 */
.tab-content {
  padding: 15px 0;
}

/* 空内容样式 */
.empty-content {
  padding: 40px 0;
}

/* 各区块卡片样式 */
.breeding-info,
.health-info,
.cert-info,
.company-info,
.company-photos {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 区块标题样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
}

/* 信息行样式 */
.info-row {
  display: flex;
  margin-bottom: 10px;
}

.info-item {
  margin-right: 30px;
  min-width: 200px;
}

.label {
  color: #606266;
  font-weight: bold;
  margin-right: 5px;
}

/* 表格操作按钮区域 */
.table-actions {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 图片容器样式 */
.cert-images, .photos-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

/* 图片项样式 */
.cert-img-item, .photo-item {
  width: 100px;
  height: 100px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.cert-img-item img, .photo-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.add-img {
  border: 1px dashed #dcdfe6;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 信息区块样式 */
.info-section {
  padding: 10px 0;
}
</style> 